package com.bw.spring.security.browser;

import com.bw.spring.security.browser.authentication.FialAuthenticationHandller;
import com.bw.spring.security.browser.authentication.SucessAuthenticationHandller;
import com.bw.spring.security.browser.authentication.ValidCodeFilter;
import com.bw.spring.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Autowired
    SecurityProperties securityProperties;
    @Autowired
    SucessAuthenticationHandller sucessAuthenticationHandller;

    @Autowired
    FialAuthenticationHandller fialAuthenticationHandller;

    @Bean
    public ValidCodeFilter validCodeFilter(){
        return  new ValidCodeFilter();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //认证
        http.addFilterBefore(validCodeFilter(), UsernamePasswordAuthenticationFilter.class).formLogin().loginPage("/imooc-signIn.html").loginProcessingUrl("/authentication/form").
                successHandler(sucessAuthenticationHandller).failureHandler(fialAuthenticationHandller)
                .and().
                authorizeRequests().
                antMatchers("/imooc-signIn.html",
                        "/authentication/form",
                        "/code/image.jpg")
                .permitAll().
                anyRequest().
                authenticated()
                .and().csrf()
                .disable();//对请求授权，对任何请求都授权
    }
}
